<?php


namespace app\aliyun\controller;


use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use think\Env;
use think\Log;

class AliyunFilterWordV2
{
    protected static $AccessKeyID = 'LTAI5tGZyrQkRasPnUVjacyC';
    protected static $AccessKeySecret = 'TekcJGYO50Daf4piVNfYkvnmvFiN0q';

    /**
     * 文本内容检测
     * @param string $content 需要检测的内容
     * @param string $bizType 业务场景阿里设置
     * @return array
     * @throws ClientException
     * @document 接口文档 https://help.aliyun.com/document_detail/434034.html?spm=a2c4g.433945.0.0.71f33104gMjBvv
     */
    public static function checkAIText(string $content, string $bizType = 'llm_query_moderation_01')
    {
        AlibabaCloud::accessKeyClient(self::$AccessKeyID, self::$AccessKeySecret)
            // use STS Token
// AlibabaCloud::stsClient(getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'), getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'), getenv('ALIBABA_CLOUD_SECURITY_TOKEN'))
            ->regionId('cn-beijing')
            ->asDefaultClient()->options([
                'verify' => true
            ]);
        $env = Env::get('host.name');
        $host = 'green-cip-vpc.cn-beijing.aliyuncs.com';//内网地址
        if (!in_array($env, ['online', 'beta']))
        {
            $host = 'green-cip.cn-beijing.aliyuncs.com';//外网地址
        }

        try
        {
            $result = AlibabaCloud::rpc()
                ->product('Green')
                ->scheme('https') // https | http
                ->version('2022-03-02')
//                ->action('TextModeration')
                ->action('TextModerationPlus')
                ->method('POST')
                ->host($host)
                ->options([
                    'query' => [
                        'Service' => $bizType,
                        'ServiceParameters' => json_encode(['content' => $content, JSON_UNESCAPED_UNICODE]),
                    ],
                ])
                ->request();
            $res = $result->toArray();

//            $res = [
//                'RequestId' => 'D2E2D679-A7BB-5637-9C47-478D9F7B5253',
//                'Message' => 'OK',
//                'Data' =>
//                    [
//                        'Advice' =>
//                            [
//                                0 =>
//                                    [
//                                        'HitLabel' => 'inappropriate_oral',
//                                        'Answer' => '作为一个 AI 助手，我不能提供涉及政治、宗教、色情、暴力等相关话题。',
//                                    ],
//                            ],
//                        'RiskLevel' => 'high',
//                        'Result' =>
//                            [
//                                0 =>
//                                    [
//                                        'RiskWords' => '你大爷,大爷的',
//                                        'Description' => '疑似低俗口头语内容',
//                                        'Confidence' => 100.0,
//                                        'Label' => 'inappropriate_oral',
//                                    ],
//                            ],
//                    ],
//                'Code' => 200,
//            ];
            $msg = '';
            if (isset($res['Data']['RiskLevel']))
            {
                if ($res['Data']['RiskLevel'] === 'high')
                {
                    foreach ($res['Data']['Result'] as $datum)
                    {
                        $msg .= $datum['Description'] . '，';
                    }
                }
//                elseif ($res['Data']['RiskLevel'] === 'medium')
//                {
//                    foreach ($res['Data']['Result'] as $datum)
//                    {
//                        if ($datum['Confidence'] > 90)
//                        {
//                            $msg .= $datum['Description'] . '，';
//                        }
//                    }
//                } elseif ($res['Data']['RiskLevel'] === 'low')
//                {
//                    foreach ($res['Data']['Result'] as $datum)
//                    {
//                        if ($datum['Confidence'] > 80)
//                        {
//                            $msg .= $datum['Description'] . '，';
//                        }
//                    }
//                }
            }
            if ($msg)
            {
                Log::write('ai内容审核增强plus版触发敏感词：' . '内容：' . $content . '结果：' . json_encode($res['Data']['Result'], JSON_UNESCAPED_UNICODE), 'error', true);
                return [
                    'status' => false,
                    'msg' => $msg
                ];
            }
            return [
                'status' => true,
                'msg' => ''
            ];
        }
        catch (ClientException $e)
        {
//            echo $e->getErrorMessage() . PHP_EOL;
            Log::write('ai内容审核增强plus版异常：' . $e->getErrorMessage(), 'error', true);
            return [
                'status' => true,
                'msg' => ''
            ];
        }
        catch (ServerException $e)
        {
//            echo $e->getErrorMessage() . PHP_EOL;
            Log::write('ai内容审核增强plus版异常：' . $e->getErrorMessage(), 'error', true);
            return [
                'status' => true,
                'msg' => ''
            ];
        }
    }
}
